<template>
  <div class="container">
    <div class="head-top">
      <span> {{symbol}}转账</span>
      <img @click="$router.back()" src="static/img/return.png" />
      <div class="read">{{parseFloat((currentAccount.ethBalance/Math.pow(10,18)).toFixed(6))}}</div>
    </div>
    <div class="body">
      <div class="label">收款人钱包地址</div>
      <mt-field placeholder="收款人钱包地址" v-model="toAddress">
        <div @click="showContact" style="position: absolute;right:-.6rem;top:-.7rem"><img
          src="static/img/contact.png" style="width: 1.4rem;height: 1.4rem"></div>
      </mt-field>
       <div class="label">转账金额 (ether)</div>
      <mt-field placeholder="转账金额 (ether)" v-model="money"></mt-field>
       <div class="label">备注</div>
      <mt-field placeholder="备注" v-model="remark"></mt-field>
    <div class="label">矿工费用</div>
      <div class="range" v-if="switchType==false">
        <div>
          <mt-range v-model="rangeValue" :min="1" :max="60" :step="1"
                    style="margin-top: 1rem;width: 90%;margin: 0px auto"></mt-range>
        </div>
        <div class="btm-title">
          <span>
            慢
          </span>
          <div>{{displayValue}} ether</div>
          <span>
            快
          </span>
        </div>
      </div>

      <div class="high" v-if="switchType" style="position: relative">
        <div
          style="position: absolute;right:0;font-size:.8rem;color:#bfbfbf;z-index: 9999;top:.7rem;right:.2rem">
          gwei
        </div>
        <div class="label">自定义Gas Price</div>
        <mt-field placeholder="自定义Gas Price" v-model="myGasPrice"></mt-field>
        <div class="label">自定义Gas</div>
        <mt-field placeholder="自定义Gas" v-model="myGasLimit"></mt-field>
        <div class="label">16进制数据</div>
        <mt-field placeholder="16进制数据" type="textarea" rows="4" v-model="hexData"
                  style="margin-top:1rem;border:1px solid rgba(0,0,0,0.1);border-bottom:none"></mt-field>
      </div>

      <div class="switch">

        <div>高级选项</div>
        <mt-switch v-model="switchType"></mt-switch>
      </div>

      <mt-button type="primary"
                 style="background: #36BAC9;display: block;width: 80%;margin:2rem auto 0rem auto"
                 @click="togglePopup">下一步
      </mt-button>

      <mt-popup id="enterPopul"
                v-model="popupVisible"
                position="bottom" style="width: 100%;padding: 0rem 0rem 1rem 0rem">

        <h3 style="margin:.5rem 0rem;text-align: center">支付详情</h3>

        <mt-field label="订单信息" readonly value="转账"
                  style="width: 90%;margin: 0px auto;border-top: 1px solid rgba(0,0,0,0.1)"></mt-field>
        <mt-field label="收款地址" readonly v-model="toAddress" style="width: 90%;margin: 0px auto"></mt-field>
        <mt-field label="付款钱包" readonly v-model="fromAddress" style="width: 90%;margin: 0px auto"></mt-field>
        <mt-field label="矿工费" readonly :value="poundage+' ETH ≈ '+(poundage*currentAccount.ethPrice*global.rate).toFixed(4) +' CNY'"
                  style="width: 90%;margin: 0px auto"></mt-field>
        <mt-field label="金额" readonly :value="money+' ETH'" style="width: 90%;margin: 0px auto"></mt-field>
        <mt-button type="primary"
                   style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
                   @click="enterPwd">确认
        </mt-button>

      </mt-popup>

      <mt-popup id="enterPopulPwd"
                v-model="popupVisiblePwd"
                position="bottom" style="width: 100%;padding: 0rem 0rem 40% 0rem">

        <h3 style="margin:.5rem 0rem;text-align: center">确认交易</h3>

        <mt-field label="密码" placeholder="请输入密码" type="password" v-model="pwd"
                  style="width: 90%;margin: 0px auto"></mt-field>
        <mt-button type="primary"
                   style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
                   @click="reEnterPwd">确认
        </mt-button>

      </mt-popup>
    </div>


    <mt-popup
      v-model="showcontact"
      popup-transition="popup-fade"
      style="width: 80%;padding:.5rem;border-radius:.3rem;overflow: hidden;">

      <div style=" position: absolute;right:1rem;top:.1rem;font-size: 1.7rem;color:gray"
           @click="showcontact=false">×
      </div>

      <div style="margin-bottom: .1rem;text-align: center">
        <!--<img src="static/img/contact.png" style="width: 1.8rem;height: 1.8rem;display: inline-block;margin-top: .3rem">-->
        <!---->
        <div
          style="font-size: 1.2rem;font-weight: 600;padding-bottom: 0.5rem; border-bottom: 0.5px solid rgba(0,0,0,0.1)">
          联系人
        </div>
      </div>

      <div v-if="!contactList||contactList.length<1" style="position:absolute; left:40%;top:40%">
        无联系人~
      </div>

      <div style="width: 100%;max-height:25rem;min-height: 8rem; overflow-x:hidden;">
        <div class="contactBox">
          <div v-for="contact,index in contactList" @click="choiceContact(contact)">
            <div><img src="static/img/contact.png"></div>
            <div>
              <div>{{contact.name}}</div>
              <div>{{contact.address}}</div>
            </div>
            <div>
              {{contact.date}}
            </div>
          </div>

        </div>
      </div>


    </mt-popup>
  </div>
</template>


<script>

  import BigNumber from 'bignumber.js'
  import Tx from 'ethereumjs-tx'
  import accountUtils from '../../service/eth/accountUtils'
  import {mapGetters, mapActions} from 'vuex'
  import {Range, Switch, Button, Popup} from 'mint-ui';
  import {Toast,Dialog} from 'vant'

  export default {
    data() {
      return {
        symbol: 'ETH',
        showcontact: false,
        popupVisible: false,
        popupVisiblePwd: false,
        switchType: false,
        rangeValue: 1,
        displayValue: 0.0000252,
        fromAddress: '',
        toAddress: '',
        money: '',
        remark: '',
        gasLimit: 25200,
        gasPrice: 1000000000,
        autoGasPrice: 0,
        myGasLimit: '',
        myGasPrice: '',
        poundage: 0,
        data: '',
        hexData: '',
        pwd: ''
      }
    },
    computed: {
      ...mapGetters(['currentAccount', 'wallet', 'accountIndex', 'messageList', 'contactList'])
    },
    created() {
      this.fromAddress = this.currentAccount.address
      this.poundage = this.rangeValue * this.gasLimit / 1000000000
    },
    methods: {
      ...mapActions(['setWalletAccountByIndex']),
      accMul(arg1,arg2) {

        return  this.convertBigNumber(new BigNumber(arg1).multipliedBy(arg2).valueOf())
      },
      accDiv(arg1,arg2){
        return  this.convertBigNumber(new BigNumber(arg1).dividedBy(arg2).valueOf())
      },
      convertBigNumber(param){
        let strParam = String(param)
        let flag = /e/.test(strParam)
        if (!flag) return param

        // 指数符号 true: 正，false: 负
        let sysbol = true
        if (/e-/.test(strParam)) {
          sysbol = false
        }
        // 指数
        let index = Number(strParam.match(/\d+$/)[0])
        // 基数
        let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, '')

        if (sysbol) {
          return basis.padEnd(index + 1, 0)
        } else {
          return basis.padStart(index + basis.length, 0).replace(/^0/, '0.')
        }
      },
      togglePopup() {
        if (!this.toAddress) {
          Dialog.alert({
            title: '提示',
            message: '请填写收款地址'
          }).then(() => {

          });
          return;
        } else if (!this.global.web3.utils.isAddress(this.toAddress)) {
          Dialog.alert({
            title: '提示',
            message: '不是有效的收款地址'
          }).then(() => {

          });
          return;
        } else if (!this.money) {
          Dialog.alert({
            title: '提示',
            message: '请填写转账金额'
          }).then(() => {

          });
          return;
        }
        if (!parseFloat(this.money)) {
          Dialog.alert({
            title: '提示',
            message: '请输入正确的数字'
          }).then(() => {

          });
          return;
        } else if (this.money > parseFloat(this.currentAccount.ethBalance * Math.pow(10, 18))) {
          Dialog.alert({
            title: '提示',
            message: '您的余额不足'
          }).then(() => {

          });
          return;
        }
        if (!this.switchType) {

          if (parseFloat(this.money) + parseFloat(this.poundage) > this.currentAccount.ethBalance/Math.pow(10, 18)) {
            Dialog.alert({
              title: '提示',
              message: '您的余额不足以支付手续费，请下调转账金额'
            }).then(() => {

            });
            return;
          }
          if (this.rangeValue <= parseInt(this.autoGasPrice / 1000000000) / 2) {

            Dialog.confirm({
              title: '提示',
              message: '手续费过低,可能会造成交易失败,要继续吗？'
            }).then(() => {
                this.popupVisible = !this.popupVisible
            })

          } else {
            this.popupVisible = !this.popupVisible
          }
        } else {
          if (this.switchType) {

            if (!this.myGasPrice) {
              Dialog.alert({
                title: '提示',
                message: '请输入Gas Price'
              }).then(() => {

              });
              return;
            } else if (parseInt(this.myGasPrice % 1) != 0 || parseInt(this.myGasPrice) < 1) {
              Dialog.alert({
                title: '提示',
                message: 'Gas Price必须为大于0的整数'
              }).then(() => {

              });
              return;
            } else if (!this.myGasLimit) {
              Dialog.alert({
                title: '提示',
                message: 'Gas Limit必须为整数'
              }).then(() => {

              });
              return;
            } else if (parseInt(this.myGasLimit % 1) != 0) {
              Dialog.alert({
                title: '提示',
                message: 'Gas Limit必须为整数'
              }).then(() => {

              });
              return;
            } else if (this.myGasLimit < 21000) {
              Dialog.alert({
                title: '提示',
                message: 'Gas Limit不能小于21000'
              }).then(() => {

              });
              return;
            } else if (this.myGasPrice / 1000000000 * this.myGasLimit + this.money > this.currentAccount.ethBalance) {
              Dialog.alert({
                title: '提示',
                message: '您的余额不足以支付手续费，请下调转账金额'
              }).then(() => {

              });
              return;
            }
            if (this.hexData != '') {
              if (!this.global.web3.utils.isHex(this.hexData.substring(0, 2) != '0x' || this.hexData.substring(2, this.hexData.length))) {
                Dialog.alert({
                  title: '提示',
                  message: '无效的16进制数据'
                }).then(() => {

                });
                return;
              }
            }

            if (this.myGasPrice < parseInt(this.autoGasPrice / 1000000000) / 2) {
              Dialog.confirm({
                title: '提示',
                message: '手续费过低,可能会造成交易失败,要继续吗？'
              }).then(() => {
                this.popupVisible = !this.popupVisible
              })
            } else {
              this.popupVisible = !this.popupVisible
            }

          }
        }
      },
      enterPwd() {
        this.popupVisible = !this.popupVisible
        this.popupVisiblePwd = !this.popupVisiblePwd
      },
      reEnterPwd() {
        let _this = this;
        if (!this.pwd) {
          _this.popupVisiblePwd=false;
          Dialog.alert({
            title: '提示',
            message: '请输入密码!'
          }).then(() => {
            // on close
          });
          return;
        } else if (this.pwd != this.currentAccount.password) {
          _this.popupVisiblePwd=false;
          _this.pwd=''
          Dialog.alert({
            title: '提示',
            message: '密码错误!'
          }).then(() => {
            // on close
          });
          return;
        }

        this.popupVisiblePwd = !this.popupVisiblePwd
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '发送中'
        });

        let nonce = _this.currentAccount.nonce;
        for (let i = 0; i < _this.currentAccount.transactionList.length; i++) {
          if (_this.currentAccount.transactionList[i].pending == true) {
            nonce += 1;
            _this.currentAccount.nonce = nonce
          }
        }
        _this.setWalletAccountByIndex(_this.currentAccount, _this.accountIndex)
        let val = parseInt(_this.global.web3.utils.toWei(_this.money + '', 'ether'))
        var rawTx = {
          nonce: nonce,
          gasPrice: this.global.web3.utils.toHex(this.gasPrice),
          gasLimit: this.gasLimit,
          to: this.toAddress,
          value: val,
          data: !_this.switchType ? _this.global.web3.utils.toHex(_this.remark) : _this.hexData
        }

        let priKey = this.currentAccount.priKey;
        if (priKey.indexOf('0x') != -1) {
          priKey = priKey.substring(2, priKey.length)
        }
        var privateKey = Buffer.from(priKey, 'hex')
        var tx = new Tx(rawTx);
        tx.sign(privateKey);
        var serializedTx = tx.serialize();

        let tran = {};

        let isAddSend = false;
        let isAddget = false;
        this.global.web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
          .on('transactionHash', function (hash) {
            console.log('交易hash:' + hash)
            tran = {

              name: 'ether',
              fromAddress: _this.currentAccount.address,
              toAddress: _this.toAddress,
              img: 'static/img/to2.png',
              error: false,
              get: false,
              txhash: hash,
              blockNumber: '',
              decimals:18,
              blockHash: '',
              date: '',
              timeStamp: (new Date().getTime() + '').substring(0, 10),
              value: _this.convertBigNumber(_this.accMul(_this.money,Math.pow(10,18)).valueOf()),
              input: !_this.switchType ? _this.global.web3.utils.toHex(_this.remark) : _this.hexData,
              pending: true
            };

            _this.currentAccount.transactionList.push(tran)
            _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
            _this.setWalletAccountByIndex(this.currentAccount, _this.accountIndex)
            Toast.clear()
            setTimeout(() => {
              _this.$router.replace({name: 'Transaction', params: {symbol: _this.symbol}})
            }, 200)

          })
          .on('receipt', function (receipt) {
            console.log(receipt)
            tran.gasMoney=_this.global.web3.utils.fromWei(parseInt(receipt.gasUsed)*1000000000+'','ether')
            tran.blockNumber=receipt.blockNumber
            tran.blockHash=receipt.blockHash

            _this.currentAccount.ethBalance-=val
            if (!isAddSend) {
              isAddSend = true;

              let message = {
                message: "转账通知: " + _this.money + " ether " + '转账成功',
                type: 'to',
                from: _this.currentAccount.address,
                to: _this.toAddress,
                timeStamp: new Date().getTime(),
                isRead: false,
                tran: tran
              }
              _this.messageList.push(message);
            }

            if (!isAddget) {
              isAddget = true;

              let message = {
                name:'ether',
                message: "收款通知: " + _this.money + " ether " + '收款成功',
                type: 'get',
                from: _this.currentAccount.address,
                to: _this.toAddress,
                timeStamp: new Date().getTime(),
                isRead: false,
                tran: tran
              }
              _this.messageList.push(message);
            }

            Toast.clear()
          })
          .on('confirmation', function (confirmationNumber, receipt) {
            console.log(confirmationNumber)
          })
          .on('error', (err) => {
            console.log(err)
            Toast.clear()
            this.pwd = ''
            return;
          });


      },
      getGasPrice() {
        let _this = this;
        _this.global.web3.eth.getGasPrice().then((price) => {

          _this.gasPrice = price*1.2
          _this.autoGasPrice = price*1.2
          _this.rangeValue = parseInt(price*1.2 / 1000000000)

        })
      },
      getNonce() {
        let _this = this;
        _this.global.web3.eth.getTransactionCount(_this.currentAccount.address).then((nonce) => {
          _this.currentAccount.nonce = nonce;
          _this.setWalletAccountByIndex(this.currentAccount, _this.accountIndex)
        })
      },
      showContact() {
        this.showcontact = true
      },
      choiceContact(contact) {
        this.toAddress = contact.address;
        this.showcontact = false;
      }
    },
    async mounted() {
      let _this = this;
      if (_this.global.web3 == '') {
        let fdStart = _this.currentAccount.priKey.indexOf('0x');
        if (fdStart != -1) {
          _this.currentAccount.priKey = _this.currentAccount.priKey.substring(2, _this.currentAccount.priKey.length);
        }
        accountUtils.initProviderFromPrivateKey(_this.currentAccount.priKey,_this.global.infuraAK).then((provide) => {
          accountUtils.initWeb3FromProvider(provide).then(({web3, provider, priKey, pubKey, address}) => {
            _this.global.setWeb3(web3)
            _this.getGasPrice()
            _this.getNonce()
          })
        })
      } else {
        this.getGasPrice()
        this.getNonce()
      }
    },
    watch: {
      rangeValue(newvalue, oldvalue) {
        this.displayValue = this.rangeValue * this.gasLimit / 1000000000;
        this.poundage = this.rangeValue * this.gasLimit / 1000000000;

      },
      myGasPrice(newvalue, oldvalue) {
        this.poundage = this.myGasPrice * this.myGasLimit / 1000000000
      },
      myGasLimit(newvalue, oldvalue) {
        this.poundage = this.myGasPrice * this.myGasLimit / 1000000000
      },
      switchType(newvalue, oldvalue) {
        if (this.switchType) {
          this.poundage = this.myGasPrice * this.myGasLimit / 1000000000
        } else {
          this.displayValue = this.rangeValue * this.gasLimit / 1000000000;
          this.poundage = this.rangeValue * this.gasLimit / 1000000000;

        }
      }
    }
  }
</script>
<style lang="less" scoped>
  @import url("../../assets/css/transactionTo.less");

</style>

